package com.shop.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtils {

    /**
     * 添加一个带有cookieName和cookieValue的Cookie对象到response中。
     * @param response HttpServletResponse对象
     * @param cookieName 要添加的cookie的名称
     * @param cookieValue 要添加的cookie的值
     * @param isDelete 如果为true，则将Cookie的最大年龄设置为0，以便在客户端上删除cookie
     */
    public static void addCookie(HttpServletResponse response,String cookieName,String cookieValue,Boolean isDelete){

        Cookie cookie = new Cookie(cookieName,cookieValue);
        cookie.setPath("/");
        if (isDelete){
            cookie.setMaxAge(0);
        }

        response.addCookie(cookie);
    }
    /**
     * 添加一个带有cookieName和cookieValue的Cookie对象到response中。
     * @param response HttpServletResponse对象
     * @param cookieName 要添加的cookie的名称
     * @param cookieValue 要添加的cookie的值
     */
    public static void addCookie(HttpServletResponse response,String cookieName,String cookieValue ){
        addCookie(response,cookieName,cookieValue,false);
    }

    /**
     * 根据cookieName获取请求中的cookie的值。
     * @param request HttpServletRequest对象
     * @param cookieName 要获取值的cookie的名称
     * @return 如果找到cookie，则返回cookie的值，否则返回null
     */
    public static String getCookieValueByName(HttpServletRequest request,String cookieName){
        Cookie[] cookies = request.getCookies();
        if (cookies!=null && cookies.length>0){
            for(Cookie cookie : cookies){
                if (cookie.getName().equalsIgnoreCase(cookieName)){
                    return cookie.getValue();
                }
            }
        }

        return null;
    }
    /**
     * 根据cookieName更新请求中的cookie的值。
     * @param request HttpServletRequest对象
     * @param cookieName 要更新的cookie的名称
     * @param newCookieValue 新的cookie的值
     * @return 如果找到cookie并更新了它，则返回true，否则返回false
     */
    public static Boolean refreshRequestCookie(HttpServletRequest request,String cookieName,String newCookieValue){

        Boolean result = false;

        Cookie[] cookies = request.getCookies();
        if (cookies!=null && cookies.length>0){
            for(Cookie cookie : cookies){
                if (cookie.getName().equalsIgnoreCase(cookieName)){
                    cookie.setValue(newCookieValue);
                    result = true;
                    break;
                }
            }
        }
        return result;
    }

}
